/** Author: JTrapp@Google.com
* (c) 10.10.2007 for comments see yabWithComments.js*/
var rootURL="http://laterrevueduciel.googlecode.com/svn/trunk/"; 
var photoRootURL="http://mw1.google.com/mw-earth-vectordb/outreach/media/yab/images/";
var numImages=424;
var today;
var currentImageId=-1; 
var kmlPlacemark; 
var map = null;
var myIcon;
var markers; 
var gptd = "<td align=\"right\"><a href=\"http://www.goodplanet.org/\" target=\"_blank\">"
    + "<img src=\""+_IG_GetImageUrl(rootURL+"images/logo_goodplanet.jpg")+"\"" 
    + "border=\"0\" alt=\"Good Planet Logo\"></img></a></div></td>";
var doms = new Array("com","co.uk","de","es","fr","it", "ja", "nl");


function init() {
    today = getId();
    tabs.alignTabs("left", 10);
    tabs.addDynamicTab("<div class='tab' id='imageTab'>"+prefs.getMsg("imageTab")+"</div>", showImageCallback);

    if (GBrowserIsCompatible()&&mapEnabled()) {
        tabs.addDynamicTab("<div class='tab' id='mapTab'>"+prefs.getMsg("mapTab")+"</div>", showMapCallback); 
    } 
}
function getId() {
    var now = new Date();
    var startDay = new Date(2007,11,5);
    var dayLen = 1000*60*60*24;
    return ((Math.ceil((now.getTime()-startDay.getTime())/dayLen)));
}

function showImageCallback(tabId){
     if(currentImageId<0) {
        _gel(tabId).innerHTML="<h1><div id=\"header\">Loading ... </div></h1><div class=\"content\" id=\"content\"></div>"
        + "<table width=\"100%\"><tr><td><div class=\"status\" id=\"status\"></div></td>"
        + gptd + "</tr></table>";
        show(getId());
    } else {
        _IG_AdjustIFrameHeight();
    }
}

var initWorkaround=0;
function showMapCallback(tabId){
    if (map==null) { 
        _gel(tabId).innerHTML="<h1><div id=\"mapHeader\">"+getChildNodeValue(kmlPlacemark, "name")+"</div></h1>"
        + "<div class=\"map\" id=\"map\" style=\"height: 380px\"></div><table width=\"100%\">"
        + "<table><tr><td><div class=\"status\" id=\"mapStatus\">"+prefs.getMsg("loadingMap")+"</div></td>"
        + gptd + "</tr></table>";
        initMap();
    } else {
        _gel("mapStatus").innerHTML =prefs.getMsg("loadingMap");
        _gel("mapHeader").innerHTML =getChildNodeValue(kmlPlacemark, "name");  
    }
    var marker=markers[currentImageId];
    if (marker==null){
        var imageLink = getElement(kmlPlacemark, "imageLink");        
        var lat = getNodeValue(kmlPlacemark, "latitude");
        var lng = getNodeValue(kmlPlacemark, "longitude");
        var description = getChildNodeValue(kmlPlacemark, "description");
        var point = new GLatLng(lat, lng);
        var imgWidth = imageLink.getAttribute("width");
        var infoWindowWidth = 182;
        var content = _gel("map");
        var contentWidth = content.offsetWidth;
        if (contentWidth>320) {
            infoWindowWidth = 240;
        }
        var width=(infoWindowWidth*8)/10;
        var height = imageLink.getAttribute("height") * width / imgWidth;
            
        var info = "<img src=\"" +photoRootURL+imageLink.firstChild.nodeValue
            +"\" width=\""+width+"\" height=\""+height+"\"><p>"+description+"</p>";
        marker = createMarker(currentImageId, point, info, infoWindowWidth);
        map.setZoom(6);
        map.panTo(point);
        if (initWorkaround==0) {
            initWorkaround=1;
        } else {
            map.panBy(new GSize(100, 150));    
        }
    } else {
        //map.setZoom(6);
        map.panTo(marker.getPoint());
        map.panBy(new GSize(100, 150));
    } 
    _gel("mapStatus").innerHTML = createEarthLink();
    _IG_AdjustIFrameHeight();
}
function getImageButtonURL(){
    var lang=prefs.getMsg("lang");
    return _IG_GetImageUrl(rootURL+"images/button_"+lang+".jpg");
}
function getURL(placemarkId){
    var lang=prefs.getMsg("lang");
    var index = 1+(placemarkId*23)%numImages;
    return rootURL+"pub/generdata/"+lang+"/yab"+index+".kml"
}
function mapEnabled(){
    var re = /http:\/\/([^\/]*).*/ 
    
    if (re.test(document.referrer)) {
        var match = re.exec(document.referrer);
        domain = match[1];
        for (var i=0; i<doms.length;i++){
            if (domain.substring(domain.length-doms[i].length)==doms[i]){
                return true;
            }
        }
    }
    return false;
}
function show(placemarkId) {
    if (placemarkId!=currentImageId) {
        currentImageId=placemarkId;
        var url = getURL(placemarkId); 
         _gel("status").innerHTML ="<a href=\""+url+"\"/>"+prefs.getMsg("loadingImage")+"</a>";
        _IG_FetchXmlContent(url, function (response) {
        if (response == null || typeof(response) != "object" ||
        response.firstChild == null){
            _gel("header").innerHTML = "<a href=\"javascript:show("+placemarkId+")\"/>"
                +prefs.getMsg("errorRetry")+"</a>";
            _gel("content").innerHTML ="<a href=\""+url+"\"/>"+url+"</a>";
        } else {
            var document = response.getElementsByTagName("Document");
            kmlPlacemark = document[0].getElementsByTagName("Placemark")[0];
           
            _gel("header").innerHTML =getChildNodeValue(kmlPlacemark, "name");
            var description = getChildNodeValue(kmlPlacemark, "description");
            var prefString="";
            var nextString="";
            var content = _gel("content");
            
            if (placemarkId > 0) {
                var prevId = placemarkId - 1;
                prefString ="<a href=\"javascript:show("+prevId+")\"><img src=\""
                    +_IG_GetImageUrl(rootURL+"images/"+prefs.getMsg("previousImage"))
                    +"\" width=\"14\" height=\"14\" alt=\""
                    +prefs.getMsg("previousTT")+"\" border=\"0\"/></a>"; 
            }
            if (placemarkId < today) {
                var nextId = placemarkId + 1;
                nextString="<a href=\"javascript:show("+nextId+")\"><img src=\""
                    +_IG_GetImageUrl(rootURL+"images/"+prefs.getMsg("nextImage"))
                    +"\" width=\"14\" height=\"14\" alt=\""
                    +prefs.getMsg("nextTT")+"\" border=\"0\"/></a>"; 
            }
            var imageLink = getElement(kmlPlacemark, "imageLink");
            var width = imageLink.getAttribute("width");

            var contentWidth = content.offsetWidth;
            var height = imageLink.getAttribute("height") * contentWidth / width;
            
            content.innerHTML = 
                "<img src=\""+photoRootURL+imageLink.firstChild.nodeValue
                + "\" width=\""+contentWidth + "\" height=\""+height
                + "\"><table width=\"100%\"<tr><td width=\"10%\" >"+prefString
                +"</td><td align=\"center\" class=\"copyright\"><a target=\"_blank\" href=\"http://www.yannarthusbertrand.com/\"> &copy; Yann Arthus-Bertrand </a></td><td align=\"right\" width=\"10%\">"
                +nextString+"</td></tr></table>"+description;            
        }  
        _gel("status").innerHTML = createEarthLink();
        _IG_AdjustIFrameHeight();    });
    } else {
        _IG_AdjustIFrameHeight();  
    }
} 
function getNodeValue(element, tagname) {
    var nodeList = element.getElementsByTagName(tagname);
    if (nodeList.length>0) {
        if (nodeList.item(0).firstChild!=null) {
                return nodeList.item(0).firstChild.nodeValue;
        } else {
                return "[<"+tagname+"> null]";
        }
    }
    return "[<"+tagname+"> not found]";
}
function getChildNodeValue(element, tagname) {
    var nodeList = element.childNodes;
    for (var i = 0, node; node = nodeList[i]; i++) {
        if (tagname==node.nodeName){
           if (node.firstChild!=null){
                   return node.firstChild.nodeValue;
            } else {
                    return "";
            }
        }
    }
    return null;
}
function getElement(element, tagname) {
    return element.getElementsByTagName(tagname).item(0);    
}
function createEarthLink() {
  if (mapEnabled()) {
    return "<a rel=\"alternate\" target=\"_blank\" href=\"http://www.google."
       +prefs.getMsg("domain")+"/"+prefs.getMsg("microsite")+"\"/><img width=\""
       +prefs.getMsg("button_width")
       +"\" height=\""+prefs.getMsg("button_height")+"\" src=\""+getImageButtonURL()
       +"\" border=\"0\" alt=\"" +prefs.getMsg("showInEarth")+"\"/></a>"; 
       } else {
   return "";
   }
}
function initMap() {
    map = new GMap2(_gel("map"));
    map.setCenter(new GLatLng(41.875696,-87.624207), 3); 
    map.addControl(new GSmallMapControl());
    map.setMapType(G_HYBRID_MAP);
    if (prefs.getBool("showMapTypeControls")) { 
        map.addControl(new GMapTypeControl());
    }

    myIcon = new GIcon();
    myIcon.iconSize = new GSize(42,42);
    myIcon.iconAnchor = new GPoint(42,42);
    myIcon.infoWindowAnchor = myIcon.iconAnchor;
    myIcon.image = _IG_GetImageUrl(rootURL+"/images/coeur64.png");
    
    markers = new Object();    
}
function createMarker(placemarkId, point, info, width) {
    var marker = new GMarker(point, {icon:myIcon});
    markers[placemarkId%numImages] = marker;
    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(info, {maxWidth : width});
    });
    map.addOverlay(marker);
 
    return marker;
}